package com.tencreat.mall.controller.app;

import com.tencreat.common.annotation.RepeatSubmit;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.enums.OrderType;
import com.tencreat.common.exception.CustomException;
import com.tencreat.domain.mall.MallCart;
import com.tencreat.domain.mall.MallOrder;
import com.tencreat.domain.mall.vo.ResOrderMallGoodsVO;
import com.tencreat.domain.mall.dto.OrderMallSubmitDTO;
import com.tencreat.domain.mall.vo.ResMallCartItem;
import com.tencreat.domain.mall.vo.ResOrderMallSubmitVO;
import com.tencreat.domain.mall.dto.MallCartAddDTO;
import com.tencreat.domain.mall.dto.MallCartEditDTO;
import com.tencreat.domain.mall.dto.MallCartPlaceDTO;
import com.tencreat.service.mall.IMallCartService;
import com.tencreat.service.mall.IMallOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author tang jun liang
 * @version 1.0
 * @date 2021/9/8 15:21
 * 购物车
 */
@Api(tags = "9-APP购物车")
@RestController
@RequestMapping("/api/cart")
public class MallCartController extends BaseController {


    @Autowired
    private final IMallCartService mallCartService;

    @Autowired
    private IMallOrderService orderService;

    public MallCartController(IMallCartService mallCartService) {
        this.mallCartService = mallCartService;
    }


    @ApiOperation(value = "获取购物车")
    @PostMapping("/list")
    public HttpResult<List<ResMallCartItem>> list() {
        return HttpResult.ok(mallCartService.apiList());
    }

    @ApiOperation(value = "修改购物车商品信息")
    @PostMapping("/edit")
    public HttpResult<Boolean> edit(@RequestBody @Validated MallCartEditDTO vo) {
        mallCartService.apiUpdate(vo);
        return HttpResult.ok();
    }

    @ApiOperation(value = "删除购物车的")
    @PostMapping("/remove")
    public HttpResult<Boolean> remove(@RequestBody ReqIdsParam id) {
        return to(mallCartService.deleteMallCartById(id));
    }

    @PostMapping("/add")
    @ApiOperation(value = "加入购物车")
    public HttpResult<Boolean> add(@RequestBody @Validated MallCartAddDTO vo) {
        mallCartService.apiAdd(vo);
        return HttpResult.ok();
    }

    @PostMapping("/place")
    @ApiOperation(value = "购物车下单")
    @RepeatSubmit
    public HttpResult<List<MallOrder>> place(@RequestBody @Validated MallCartPlaceDTO ro) {
        //生成多个订单造成支付宝支付时金钱不一致
//        List<MallOrder> results = orderService.cartPlaceOrder(ro);
        List<MallOrder> results = new ArrayList<>();
        OrderMallSubmitDTO order = new OrderMallSubmitDTO();
        order.setRemark(ro.getCartPlaces().get(0).getRemark());
        order.setLogistics(true);
        order.setOrderType(OrderType.SHOP);
        order.setShoppingCart(true);
        order.setType("1");
        //营销产品ID 普通商品为0
        order.setShopId(0);
        //存收货地址id
        order.setAddressId(Math.toIntExact(ro.getAddressId()));

        // 拼接id，重复检查
        StringBuilder ids = new StringBuilder();
        List<Long> id = new ArrayList<>();
        Map<Long, String> map = new HashMap<>();
        for (MallCartPlaceDTO.CartPlacePr item : ro.getCartPlaces()) {
            map.put(item.getId(), item.getRemark());
            ids.append(item.getId());
            ids.append(",");
            id.add(Long.valueOf(item.getId()));
        }
        ids.append(0);
        if (map.keySet().size() != ro.getCartPlaces().size()) {
            throw new CustomException("购物车ID重复");
        }
        // 锁购物车数据
        List<MallCart> list = mallCartService.selectForUpdate(ids.toString());
        if (ro.getCartPlaces().size() != list.size()) {
            throw new CustomException("购物车中的商品已失效或其他异常，请刷新后重试！");
        }
        ArrayList<ResOrderMallGoodsVO> pos = new ArrayList<>();
        for(MallCart  cart : list){
            ResOrderMallGoodsVO orderMallGoodsPO = new ResOrderMallGoodsVO();
            orderMallGoodsPO.setGoodsId(cart.getGoodsId());
            orderMallGoodsPO.setGoodsNum(cart.getNumber());
            orderMallGoodsPO.setGoodsSpecId(cart.getNormsId().intValue());
            pos.add(orderMallGoodsPO);
        }
        order.setGoods(pos);
        if(ro.getPriceTotal() != null){
            order.setPriceTotal(ro.getPriceTotal());
        }

        HttpResult<ResOrderMallSubmitVO> submit = orderService.submit(order, getLoginCheck());
        MallOrder eq = orderService.lambdaQuery().eq(MallOrder::getOrderSn, submit.getData().getOrderSn()).one();
        results.add(eq);
        mallCartService.deleteMallCartByIds(new ReqIdsParam(id));
        return HttpResult.ok(results);
    }

}
